package com.myschool.server.manager.impl;

import java.util.Date;
import java.util.List;

import org.myschool.common.exception.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myschool.server.dao.SectionDao;
import com.myschool.server.dao.SubjectDao;
import com.myschool.server.dao.TimeTableDao;
import com.myschool.server.dao.UserDao;
import com.myschool.server.dao.support.BaseEntityDaoHibernate;
import com.myschool.server.manager.BaseManager;
import com.myschool.server.manager.TimetableManager;
import com.myschool.server.model.TimeTableEntry;
import com.myschool.server.model.TimeTableType;

@Service
@Transactional
public class TimetableManagerImpl extends BaseManager<TimeTableEntry> implements
		TimetableManager {

	@Autowired
	private TimeTableDao timeTableDao;
	@Autowired
	private UserDao userDao;

	@Autowired
	private SubjectDao subjectDao;
	@Autowired
	private SectionDao sectionDao;

	@Override
	protected BaseEntityDaoHibernate getDao() {

		return (BaseEntityDaoHibernate) this.timeTableDao;
	}

	public List<TimeTableEntry> retrieveTimeTableBySection(int sectionID) {
		List<TimeTableEntry> persistedUser = this.timeTableDao
				.retrieveTimeTableBySection(sectionID);
		return persistedUser;

	}

	public List<TimeTableEntry> retrieveTimeTableEntriesByDate(
			Integer sectionId, Date startingFrom, short days)
			throws ApplicationException {
		List<TimeTableEntry> entries = this.timeTableDao
				.retrieveTimeTableByDate(sectionId, startingFrom, days);
		return entries;
	}

	@Transactional(rollbackFor = ApplicationException.class, readOnly = false)
	public void createTimeTable(List<TimeTableEntry> entries)
			throws ApplicationException {

		for (TimeTableEntry entry : entries) {

			entry.setSection(this.sectionDao.get(entry.getSection().getEntityId()));

			entry.setSubject(this.subjectDao.get(entry.getSubject().getEntityId()));

			if (entry.getUserAssigned() != null
					&& entry.getUserAssigned().getEntityId() != null) {
				entry.setUserAssigned(this.userDao.get(entry.getUserAssigned()
						.getEntityId()));
			}

			this.timeTableDao.save(entry);

		}

	}

	public List<TimeTableEntry> retrieveTimeTableBySchoolSectionDate(
			Integer schoolId, Integer sectionID, TimeTableType type,
			Date startingFrom) throws ApplicationException {
		List<TimeTableEntry> entries = this.timeTableDao
				.retrieveTimeTableBySchoolSectionDate(schoolId, sectionID,
						startingFrom, type);
		return entries;
	}

}
